﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace Journeo_backend.Configuration
{
    public class JwtHelper
    {
        public JwtConfig JwtConfig { get; set; }
        public readonly IHttpContextAccessor HttpContext;

        public JwtHelper(IHttpContextAccessor httpContext)
        {
            HttpContext = httpContext;
        }

        /// <summary>
        /// 添加Jwt服务
        /// </summary>
        public void AddJwtService(IServiceCollection services)
        {
            services.AddAuthentication(option =>
            {
                //认证middleware配置
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    //Token颁发机构
                    ValidIssuer = JwtConfig.Issuer,
                    //颁发给谁
                    ValidAudience = JwtConfig.Audience,
                    //这里的key要进行加密
                    IssuerSigningKey = JwtConfig.SymmetricSecurityKey,
                    //是否验证Token有效期，使用当前时间与Token的Claims中的NotBefore和Expires对比
                    ValidateLifetime = true,
                };
            });
        }

        /// <summary>
        /// 返回
        /// </summary>
        /// <returns></returns>
        public string GetJwtToken()
        {
            var claims = new List<Claim>();
            var jwtSecurityToken = new JwtSecurityToken(
                    JwtConfig.Issuer,
                    JwtConfig.Audience,
                    claims,
                    JwtConfig.NotBefore,
                    JwtConfig.Expiration,
                    JwtConfig.SigningCredentials
                );
            var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            return token;
        }

        // 使用UserId、Username、PasswordHash生成Token
        public string GetJwtToken(User user)
        {
            var claims = new List<Claim>
            {
                new Claim("UserId", user.UserId.ToString()),
                new Claim("Username", user.Username),
                new Claim("Password", user.Password)
            };
            var jwtSecurityToken = new JwtSecurityToken(
                    JwtConfig.Issuer,
                    JwtConfig.Audience,
                    claims,
                    JwtConfig.NotBefore,
                    JwtConfig.Expiration,
                    JwtConfig.SigningCredentials
                );
            var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            return token;
        }

        // 获取UserId
        public long GetUserId()
        {
            var userId = 0L;
            var identity = (ClaimsIdentity)HttpContext.HttpContext.User.Identity;
            if (identity == null)
            {
                return userId;
            }
            IEnumerable<Claim> claims = identity.Claims;
            foreach (var claim in claims)
            {
                if (claim.Type == "UserId")
                {
                    userId = long.Parse(claim.Value);
                    break;
                }
            }
            return userId;
        }
    }
}
